package com.jj.core.utils;

public class BinUtils {
    public static Byte bool2Byte(Boolean value){
        if(value){
            return 0b1;
        }else{
            return 0b0;
        }
    }

    public static Integer bool2Int(Boolean value){
        if(value){
            return 1;
        }else{
            return 0;
        }
    }

    public static Boolean toBool(Byte value){
        return value!=0;
    }

    public static Boolean toBool(Integer value){
        return value.intValue()!=0;
    }

    public static Boolean toBool(Long value){
        return value.longValue()!=0;
    }



    public static Integer toInt(byte[] data, int offset) {
        if (data == null) {
            return null;
        } else {
            return  (data[offset]     & 0xff) << 24 |
                    (data[offset + 1] & 0xff) << 16 |
                    (data[offset + 2] & 0xff) <<  8 |
                    data[offset + 3] & 0xff;
        }
    }

    public static Long toLong(byte[] data, int offset) {
        if (data == null) {
            return null;
        } else {
            return  ((long) data[offset]     & 0xff) << 56 |
                    ((long) data[offset + 1] & 0xff) << 48 |
                    ((long) data[offset + 2] & 0xff) << 40 |
                    ((long) data[offset + 3] & 0xff) << 32 |
                    ((long) data[offset + 4] & 0xff) << 24 |
                    ((long) data[offset + 5] & 0xff) << 16 |
                    ((long) data[offset + 6] & 0xff) <<  8 |
                    (long) data[offset + 7] & 0xff;
        }
    }


    public static Short toShort(byte[] data, int offset) {
        if (data == null) {
            return null;
        } else {
            return (short) (data[offset] << 8 | data[offset + 1] & 0xFF);
        }
    }


    public static byte[] fromInt(int value) {
        byte[] array = new byte[4];

        array[0]     = (byte) (value >>> 24);
        array[0 + 1] = (byte) (value >>> 16);
        array[0 + 2] = (byte) (value >>> 8);
        array[0 + 3] = (byte) value;

        return array;
    }


    public static byte[] fromShort(short value) {
        byte[] array = new byte[2];
        int index = 0;
        array[index]     = (byte) (value >>> 8);
        array[index + 1] = (byte) value;
        return array;
    }

    public static void fromLong(long value, byte[] array, int index) {
        array[index]     = (byte) (value >>> 56);
        array[index + 1] = (byte) (value >>> 48);
        array[index + 2] = (byte) (value >>> 40);
        array[index + 3] = (byte) (value >>> 32);
        array[index + 4] = (byte) (value >>> 24);
        array[index + 5] = (byte) (value >>> 16);
        array[index + 6] = (byte) (value >>> 8);
        array[index + 7] = (byte) value;
    }

}
